/**
 * @Time    : 2021/7/6/006 16:41
 * @Author  : WanRongJia
 * @License : Software business license
 * @Site    : www.rich-f.com
 * @File    : findOneAndSave.js
 * @Software: Rich Web Platform
 * @Function: 修改单条数据
 * @Version : 1.0
 **/

let logger = require('log4js').getLogger("default");
const { buildErrObject } = require('./buildErrObject')
const { itemNotFound } = require('./itemNotFound')
/**
 *
 * @param model 数据库model
 * @param query 查询条件
 * @param sets 要修改的数据
 */
const findOneAndSave = (model = {}, query = {}, sets = {}, message = 'NOT_FOUND') => {
    return new Promise((resolve, reject) => {
        model.findOne(query, async (err, doc) => {
            try {
                await itemNotFound(err, doc, message)
                Object.keys(sets).forEach(item => {
                    doc[item] = sets[item]
                })
                doc.save((err) => {
                    if (err) {
                        return reject(buildErrObject(422, err.message))
                    }
                    resolve(doc)
                })
            } catch (err) {
                logger.error(err)
                reject(buildErrObject(422, err.message))
            }
        })
    })
}

module.exports = { findOneAndSave }